package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProp;

    @PostMapping("accredit")
    public ResponseEntity<Void> accredit(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response){
        String token = this.authService.accredit(username,password,jwtProp);

        if (StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }


        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request, response, jwtProp.getCookieName(),
                token, jwtProp.getCookieMaxAge(), null, true);


        return ResponseEntity.ok().build();
    }

    @GetMapping("verify")//直接从request对象中获取cookie名字为LY_TOKEN的cookie
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN")String token,HttpServletRequest request,HttpServletResponse response){


        //使用公钥解析cookie
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token,jwtProp.getPublicKey());

            String newToken = JwtUtils.generateToken(userInfo, jwtProp.getPrivateKey(), jwtProp.getExpire());


            //把新生成的token存入到cookie中并从当前开始计时，完成了刷新cookie同时刷新token的任务
            CookieUtils.setCookie(request,response,jwtProp.getCookieName(),newToken,jwtProp.getCookieMaxAge(),null,true);

            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //401
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();


    }

}
